<?php

namespace app\api\service;

use app\api\lib\enum\OrderStatusEnum;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderServer;
use app\api\service\Token as TokenServer;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use think\Loader;
use think\Log;

//Loader::import('WxPay.WxPay', EXTEND_PATH, '.Data.php');
Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class Pay
{

    private $orderNo;
    private $order_id;
    private $order_model = [];

//    private $orderModel;

    /**
     * 设置订单号
     * @param type $order_id
     * @throws Exception
     */
    function __construct($order_id)
    {
        if (!empty($order_id))
        {
            $this->order_id = $order_id;
            $order_model = OrderModel::get($order_id);
            $this->orderNo = $order_model->order_no;
        }
        else
        {
            throw new OrderException();
        }
    }

    public function pay()
    {
//        检测订单合理性
        $this->checkOrderValid();
//        检测库存
        (new OrderServer)->checkOrderStock($this->order_id);
        return $this->makeWxPreOrder($status['orderPrice']);
    }

    // 构建微信支付订单信息
    private function makeWxPreOrder($totalPrice)
    {
        
    }

    //向微信请求订单号并生成签名
    private function getPaySignature($wxOrderData)
    {
        
    }

    private function recordPreOrder($wxOrder)
    {
        
    }

    // 签名
    private function sign($wxOrder)
    {
        
    }

    /**
     * 检测订单合法性,是否存在,用户,支付状态
     * @return bool
     * @throws OrderException
     * @throws TokenException
     */
    private function checkOrderValid()
    {
        $order_model = $this->order_model;
        if (empty($order_model))
        {
            throw new OrderException();
        }
//        检测订单所属
        TokenServer::isValidOperate($order_model->user_id);
//        检测订单支付状态
        if ($order->status != OrderStatusEnum::UNPAID)
        {
            $option = [
                'msg' => '订单已支付过啦',
                'errorCode' => 80003,
                'code' => 400
            ];
            throw new OrderException($option);
        }
        return true;
    }

}
